<?php
namespace app\admin\controller;

use app\BaseController;
use app\common\model\Admin;
use app\common\model\AdminLoginLog;
use think\facade\View;

class Login extends BaseController
{
    protected $middleware = ['load_lang_pack'];
    
    private $cModel;
    
    public function initialize()
    {
        $this->cModel = new Admin();
    }
    
    /**
     * @Title: index
     * @Description: todo(后台登录页)
     * @return string
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    public function index()
    {
        $admin_id = session('admin_id');
        if (!empty($admin_id)){
            return redirect((string) url('index/index'));
        }else{
            return View::fetch();
        }
    }
    
    /**
     * @Title: checkLogin
     * @Description: todo(验证登录)
     * @return string
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    public function checkLogin()
    {
        if(request()->isPost()){
            $data = input('post.');
            if(!captcha_check($data['captcha'])){
                return ajax_return(lang('captcha_error'));
            };
            if (cookie('admin_username')){
                $data['username'] = cookie('admin_username');
            }
            if(empty($data['username']) || empty($data['password'])){
                return ajax_return(lang('admin_require'));
            }
            $where = [['username', '=', $data['username'] ]];
            $adminData = $this->cModel->where($where)->find();
            if(!empty($adminData)){
                if($adminData['status'] != '1'){
                    return ajax_return(lang('admin_stop'));
                }elseif(0 && $adminData['password'] != md5($data['password'])){
                    return ajax_return(lang('password_error'));
                }else{
                    $this->updateUser($adminData);   //更新登录信息
                    $this->setSession($adminData);   //设置session,cookie
                    $this->loginLog($adminData);     //登录日志
                    return ajax_return(lang('login_success'), url('index/index'));
                }
            }else{
                return ajax_return(lang('admin_empty'));
            }
        }
    }
    
    /**
     * @Title: updateUser
     * @Description: todo(更新登录信息)
     * @param array $adminData
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    private function updateUser($adminData)
    {
        $data = [
            'logins' => $adminData['logins']+1,
            'last_time' => time(),
            'last_ip' => request()->ip(),
        ];
        $this->cModel->where('id', $adminData['id'])->update($data);
    }
    
    /**
     * @Title: setSession
     * @Description: todo(设置登录信息)
     * @param array $adminData
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    private function setSession($adminData)
    {
        session('admin_id', $adminData['id']);
        if (!empty($adminData['name'])){
            cookie('admin_name', $adminData['name']);
        }else{
            cookie('admin_name', $adminData['username']);
        }
        cookie('admin_username', $adminData['username']);
        cookie('admin_avatar', $adminData['avatar']);
    }
    
    /**
     * @Title: loginLog
     * @Description: todo(记录登录信息)
     * @param array $adminData
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    private function loginLog($adminData)
    {
        $login_log = config('dbconfig.sys.login_log');
        if ($login_log == 1){
            $ip = request()->ip();
            $ipArr = file_get_contents("http://api.map.baidu.com/location/ip?ip=".$ip."&ak=EdkDmhIhuQCzpRogbaPYbGmteId8cd5G");
            $ipArr = json_decode($ipArr, true);
            if ($ipArr['status'] == '0'){
                $adminLoginLogModel = new AdminLoginLog();
                $data = [
                    'uid' => $adminData['id'],
                    'ip' => $ip,
                    'country' => '',                                                    //国家
                    'province' => $ipArr['content']['address_detail']['province'],      //省
                    'city' => $ipArr['content']['address_detail']['city'],              //城市
                    'district' => $ipArr['content']['address_detail']['district'],      //地区
                ];
                $adminLoginLogModel->save($data);
            }
        }
    }
    
    /**
     * @Title: loginOut
     * @Description: todo(退出登录)
     * @return string
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    public function loginOut()
    {
        session('admin_id', null);
        cookie('admin_name', null);
        cookie('admin_username', null);
        cookie('admin_avatar', null);
        return redirect((string) url('login/index'));
    }
    
    /**
     * @Title: loginLock
     * @Description: todo(锁定登录)
     * @return string
     * @author 刀客源码 <654108442@qq.com>
     * @date 2020年10月6日
     * @throws
     */
    public function loginLock()
    {
        session('admin_id', null);
        return redirect((string) url('login/index'));
    }
}